<?php

namespace addons\kuerp\controller;

use addons\kuerp\model\Commonseal;
use addons\kuerp\model\Event;
use addons\kuerp\model\Message as MessageModel;
use addons\kuerp\model\Notice;
use addons\kuerp\model\ExamineRecord;
use addons\kuerp\model\Record;
use addons\kuerp\model\ReceivablesPlan;
use addons\kuerp\model\Flows;
use addons\kuerp\model\GoodsSales;
use addons\kuerp\model\Expense;
use addons\kuerp\model\ScoreApply;
use app\admin\model\department\Admin;
use app\admin\model\kuerp\StaffMember;
use think\Db;

/**
 * 通知接口
 */
class Message extends StaffApi {
	protected $noNeedLogin = [];
	protected $noNeedRight = [];


	//获取工作报告通知列表
	public function getWorkreportMessage() {
		$limit = input("limit/d", 10);

		$where = ['to_staff_id' => $this->auth->id, 'relation_type' => MessageModel::WORKREPORT_TYPE];

		$records = MessageModel::where($where)
            ->with(['fromStaff','examine','workreport'])
            ->order('status asc,id desc')
            ->field('id,from_staff_id,relation_id,status,content,send_time')->paginate($limit);

		$this->success('请求成功', $records);
	}

    //待办日程
	public function getStartEvent(){
        //待办日程
        $eventWhere = [
            'status' => ['in', [0, 1]],
            'start_time' => ['lt', date('Y-m-d', strtotime('+1 day'))],
//            'end_time' => ['gt', date('Y-m-d H:i:s')],
            'staff_id' => $this->auth->id,
        ];
        $event = Event::where($eventWhere)->with([
            'staff',
            'customer',
        ])->order('id desc')->select();
        $event=collection($event)->toArray();
        foreach ($event as $k => $v) {
            $v['level'] = Event::getLevel($v['level']);
            $v['status'] = Event::getStatus($v['status']);

            $event[$k] = $v;
        }
        $this->success('请求成功', $event);
    }

    //逾期日程
	public function getOverEvent(){
        //逾期日程
        $overEventsWhere=[
            'start_time' => ['lt', date('Y-m-d', strtotime('+1 day'))],
            'end_time' => ['lt', date('Y-m-d H:i:s')],
            'status'   => ['in', [0, 1]],
            'staff_id'=>$this->auth->id,
        ];

        $event = Event::where($overEventsWhere)->with([
            'staff',
            'customer'
        ])->order('id desc')->select();
        $event=collection($event)->toArray();
        foreach ($event as $k => $v) {
            $v['level'] = Event::getLevel($v['level']);
            $v['status'] = Event::getStatus($v['status']);

            $event[$k] = $v;
        }
        $this->success('请求成功', $event);
    }

    //工作动态
    public function getWorkSignin(){
        $limit = input("limit/d", 10);

        $where = ['to_staff_id' => $this->auth->id, 'relation_type' => MessageModel::RECORD_TYPE];

        $records = MessageModel::where($where)
            ->with(['fromStaff','examine'])
            ->order('status asc,id desc')->paginate($limit);

        $this->success('请求成功', $records);
    }

    //发送传阅消息
    public function sendMessage(){
        $relation_type=input('relation_type');
        $relation_id=input('relation_id');
        $staff_id=input('staff_id');
        $staff_ids=explode(',',$staff_id);

        $model=new MessageModel();
        switch ($relation_type) {
            case $model::CONSUME_TYPE://费用
                $rowModel = new \addons\kuerp\model\Consume();
                break;
            case $model::CONTRACT_TYPE://合同
                $rowModel = new \addons\kuerp\model\Contract();
                break;
            case $model::RECEIVABLES_TYPE://回款
                $rowModel = new \addons\kuerp\model\Receivables();
                break;
            case $model::ACHIEVEMENT_TYPE://业绩目标
                $rowModel = new \addons\kuerp\model\AchievementRecords();
                break;
            case $model::EVENT_TYPE://日程
                $rowModel = new \addons\kuerp\model\Event();
                break;
            case $model::QUOTE_TYPE://报价单
                $rowModel = new \addons\kuerp\model\Quote();
                break;
            case $model::CUSTOMER_TYPE://客户
                $rowModel = new \addons\kuerp\model\Customer();
                break;
            case $model::APPROVAL_TYPE://审批
                $rowModel = new \addons\kuerp\model\Approval();
                break;
            case $model::PARTS_TYPE://配件
                $rowModel = new \addons\kuerp\model\Parts();
                break;
            case $model::PARTS_STOCK_RELOAD_TYPE://配件
                $rowModel = new \addons\kuerp\model\PartsStockReload();
                break;
            default:
                $this->error('参数错误');
        }
        $row=$rowModel->get($relation_id);
        if(empty($row)){
            $this->error('信息不存在');
        }
        switch ($relation_type) {
            case $model::CONSUME_TYPE://费用
                $content=$this->auth->name."传阅费用《{$row['number']}》，邀请您审阅";
                break;
            case $model::CONTRACT_TYPE://合同
                $content=$this->auth->name."传阅合同《{$row['num']}》，邀请您审阅";
                break;
            case $model::RECEIVABLES_TYPE://回款
                $content=$this->auth->name."传阅回款《{$row['number']}》，邀请您审阅";
                break;
            case $model::ACHIEVEMENT_TYPE://业绩目标
                $content=$this->auth->name."传阅目标《{$row['year']}》，邀请您审阅";
                break;
            case $model::EVENT_TYPE://日程
                $content=$this->auth->name."传阅{$row['event_type']}《{$row['title']}》，邀请您审阅";
                break;
            case $model::PROOF_TYPE://打样
                $content=$this->auth->name."传阅打样《{$row['process_number']}》，邀请您审阅";
                break;
            case $model::QUOTE_TYPE://报价单
                $content=$this->auth->name."传阅报价单《{$row['number']}》，邀请您审阅";
                break;
            case $model::CUSTOMER_TYPE://客户
                $content=$this->auth->name."传阅客户《{$row['name']}》，邀请您审阅";
                break;
            case $model::APPROVAL_TYPE://审批
                $content=$this->auth->name."传阅审批，邀请您审阅";
                break;
            case $model::PARTS_TYPE://配件
                $content=$this->auth->name."传阅配件信息，邀请您审阅";
                break;
            case $model::PARTS_STOCK_RELOAD_TYPE://配件
                $content=$this->auth->name."传阅配件信息，邀请您审阅";
                break;
            default:
                $this->error('参数错误');
        }

        foreach ($staff_ids as $id){
            MessageModel::addMessage($relation_type,$relation_id,$id, $this->auth->id, $content);
        }

        $this->success('请求成功');
    }


    /**
     * 获取通知列表
     */
    public function getList()
    {
        $limit = input("limit/d", 10);

        $where = ['to_staff_id' => $this->auth->id ,'relation_type'=>['neq',MessageModel::EXAMINE_TYPE]];
        $records = MessageModel::where($where)->with(['fromStaff', 'examine'])->order('status asc,id desc')->paginate($limit);

        $this->success('请求成功', $records);
    }

    /**
     * 获取审批列表
     */
    public function getExamineRecord()
    {
        $limit = input("limit/d", 10);
        //合同审批，回款审批、业绩目标审批、办公审批 费用
        $relation_type = input('type');
        $status =  input('status',0);
        if($status == 1){
            $status = array('in','2,3');
        }
        $ids = ExamineRecord::where(['relation_type' => $relation_type,
            'status' => $status,
            'check_staff_id' => $this->auth->id])->column('id');
        $where = ['to_staff_id' => $this->auth->id, 'relation_id' => ['in', $ids], 'relation_type' => MessageModel::EXAMINE_TYPE];

        $records = MessageModel::where($where)->with(['fromStaff', 'examine'])->order('status asc,id desc')->paginate($limit);

        $this->success('请求成功', $records);
    }

    /**
     * 获取审批通知详情
     */
    public function getExamineInfo()
    {

        $data = [
            ExamineRecord::CONTRACT_TYPE => ['count' => 0, 'msg' => '暂无消息'],
            ExamineRecord::EXPENSE_TYPE => ['count' => 0, 'msg' => '暂无消息'],
            ExamineRecord::SCORE_TYPE => ['count' => 0, 'msg' => '暂无消息'],
            ExamineRecord::COMMONSEAL_TYPE => ['count' => 0, 'msg' => '暂无消息'],
            // ExamineRecord::CONSUME_TYPE => ['count' => 0, 'msg' => '暂无消息'],
            // ExamineRecord::RECEIVABLES_TYPE => ['count' => 0, 'msg' => '暂无消息'],
            // ExamineRecord::APPROVAL_TYPE => ['count' => 0, 'msg' => '暂无消息'],
            // ExamineRecord::ACHIEVEMENT_TYPE => ['count' => 0, 'msg' => '暂无消息'],
            // ExamineRecord::CARD_TYPE => ['count' => 0, 'msg' => '暂无消息'],
            // ExamineRecord::LEAVE_TYPE => ['count' => 0, 'msg' => '暂无消息'],

            // ExamineRecord::QUOTE_TYPE => ['count' => 0, 'msg' => '暂无消息'],
            // ExamineRecord::PARTS_TYPE => ['count' => 0, 'msg' => '暂无消息'],
            // ExamineRecord::INVOICE_TYPE => ['count' => 0, 'msg' => '暂无消息'],
            // ExamineRecord::DELIVERY_TYPE => ['count' => 0, 'msg' => '暂无消息'],
            // ExamineRecord::INSTOCK_TYPE => ['count' => 0, 'msg' => '暂无消息'],
            // ExamineRecord::OUTSTOCK_TYPE => ['count' => 0, 'msg' => '暂无消息'],
        ];
        //系统设置特定审核人员
        $config_examine_admins = config('site.examine_admins');
        $adminids = $this->auth->adminids;
        $sale_users = $this->auth->sale_users;
        if (!empty($config_examine_admins[$this->auth->id])) {
            $adminids = array_merge($adminids,explode(',', $config_examine_admins[$this->auth->id]));
            //获取对应销售id
            $config_sale_users = (new StaffMember())->getStaffMemberIds($adminids);
            $sale_users = array_merge($sale_users,$config_sale_users);
        }
        foreach ($data as $type=>$v) {
            $ids = [];
            switch ($type) {
                case ExamineRecord::CONTRACT_TYPE:
                    $flows = Flows::where('relation_type', 'goods_sale')->where('status', 1)->find();
                    $examine_index = 0;
                    $last_examine_indexs = [];
                    if (!empty($flows)){
                        $flows['flow_items'] = json_decode($flows['flow_items'], true);
                        //判断流程中是否有当前用户审核
                        foreach ($flows['flow_items'] as $key => $value) {
                            if (in_array($this->auth->id, explode(',',$value['admin_id'])) ) {
                                $examine_index = $key + 1;
                                $last_examine_indexs[] = $key;
                                // break;
                            }
                        }
                    }
                    if ($examine_index > 0) {
                        //当前用户存在多级审核且存在第一级审核时 需要获取该用户的直属下级
                        $first_children_ids = [];
                        $search_index = array_search(0, $last_examine_indexs);
                        if(count($last_examine_indexs) > 1 && $search_index !== false) {
                            //获取直属下级
                            $department_ids = Admin::getPrincipalIds($this->auth->id);
                            if ($department_ids) {
                                $children_ids = Admin::getDepartmentAdminIds($department_ids, true);
                                $children_ids = !empty($config_examine_admins[$this->auth->id]) ? array_merge($children_ids, explode(',', $config_examine_admins[$this->auth->id])) : $children_ids;
                                if ($children_ids) {
                                    $first_children_ids = (new StaffMember())->getStaffMemberIds($children_ids);
                                }
                            }
                            $last_examine_indexs = array_values(array_diff($last_examine_indexs, [0]));
                        }
                        $saleWhere = [];
                        if ($sale_users) {
                            $saleWhere['sale_user'] = ['IN', implode(',', $sale_users)];
                        }
                        $saleWhere['examine_status'] = '0';
                        if (!empty($first_children_ids)) {
                            if ($last_examine_indexs) {
                                $saleWhere['id'] = ['exp', Db::raw('> 0 and ( (examine_index = 0 and sale_user in ('.implode(',', $first_children_ids).'))  OR (examine_index '.(count($last_examine_indexs) == 1 ? '='.$last_examine_indexs[0] : ' in ('.implode(',', $last_examine_indexs).')').' and sale_user in ('.implode(',', $sale_users).')))')];
                            } else {
                                $saleWhere['examine_index'] = 0;
                            }
                        } else {
                            $saleWhere['examine_index'] = count($last_examine_indexs) == 1 ? $last_examine_indexs[0] : ['in', $last_examine_indexs];
                        }
                        // $saleWhere['examine_index'] = ['in', $last_examine_indexs];//['<', $examine_index];
                        // if ($examine_index == count($flows['flow_items'])) {
                        //     $saleWhere['examine_index'] = ['>', 0];
                        // }
                        $saleWhere['examine_adminids'] = ['exp', Db::raw('="" OR FIND_IN_SET('.$this->auth->id.',examine_adminids) = 0')];
                        $ids = GoodsSales::where($saleWhere)->column('id');
                    }
                    break;
                case ExamineRecord::EXPENSE_TYPE:
                    $wheres = [
                        'admin_id' => ['in', $adminids],
                        'check_status' => 1,
                        'check_uids' => ['exp', Db::raw('="" OR FIND_IN_SET('.$this->auth->id.',check_uids) = 0')],
                    ];
                    //获取审批流程
                    $flows = Db::name('flows')->where('relation_type', 'expense')->where('status', 1)->find();
                    if (!empty($flows)){
                        $flows['flow_items'] = json_decode($flows['flow_items'], true);
                        //判断流程中是否有当前用户审核
                        $examine_index = 0;
                        foreach ($flows['flow_items'] as $key => $value) {
                            if (in_array($this->auth->id, explode(',',$value['admin_id'])) ) {
                                $examine_index = $key + 1;
                                // break;
                            }
                        }
                        if ($examine_index > 0) {
                            $wheres['check_step_sort'] = $examine_index - 1;
                            $ids = Expense::where($wheres)->column('id');
                        }
                    }
                    break;
                case ExamineRecord::SCORE_TYPE:
                    $wheres = [
                        'admin_id' => ['in', $adminids],
                        'check_status' => 1,
                        'check_uids' => ['exp', Db::raw('="" OR FIND_IN_SET('.$this->auth->id.',check_uids) = 0')],
                    ];
                    //获取审批流程
                    $flows = Db::name('flows')->where('relation_type', 'score')->where('status', 1)->find();
                    if (!empty($flows)){
                        $flows['flow_items'] = json_decode($flows['flow_items'], true);
                        //判断流程中是否有当前用户审核
                        $examine_index = 0;
                        $last_examine_indexs = [];
                        foreach ($flows['flow_items'] as $key => $value) {
                            if (in_array($this->auth->id, explode(',',$value['admin_id'])) ) {
                                $examine_index = $key + 1;
                                $last_examine_indexs[] = $key;
                                // break;
                            }
                        }
                        
                        if ($examine_index > 0) {
                            $first_children_ids = [];
                            //当前用户存在多级审核且存在第一级审核时 需要获取该用户的直属下级
                            $search_index = array_search(0, $last_examine_indexs);
                            if(count($last_examine_indexs) > 1 && $search_index !== false) {
                               //获取直属下级
                                $department_ids = Admin::getPrincipalIds($this->auth->id);
                                if ($department_ids) {
                                    $children_ids = Admin::getDepartmentAdminIds($department_ids, true);
                                    $children_ids = !empty($config_examine_admins[$this->auth->id]) ? array_merge($children_ids, explode(',', $config_examine_admins[$this->auth->id])) : $children_ids;
                                    $first_children_ids = $children_ids ?? [];
                                }
                                $last_examine_indexs = array_values(array_diff($last_examine_indexs, [0]));
                            }
                            if (!empty($first_children_ids)) {
                                if ($last_examine_indexs) {
                                    $wheres['id'] = ['exp', Db::raw('> 0 and ( (check_step_sort = 0 and admin_id in ('.implode(',', $first_children_ids).'))  OR (check_step_sort '.(count($last_examine_indexs) == 1 ? '='.$last_examine_indexs[0] : ' in ('.implode(',', $last_examine_indexs).')').' and admin_id in ('.implode(',', $adminids).')))')];
                                } else {
                                    $wheres['check_step_sort'] = 0;
                                }
                            } else {
                                $wheres['check_step_sort'] = count($last_examine_indexs) == 1 ? $last_examine_indexs[0] : ['in', $last_examine_indexs];
                            }
                            // $wheres['check_step_sort'] = $examine_index - 1;
                            $ids = ScoreApply::where($wheres)->column('id');
                        }
                    }
                    break;
                case ExamineRecord::COMMONSEAL_TYPE:
                    $wheres = [
                        'admin_id' => ['in', $adminids],
                        'check_status' => 1,
                        'check_uids' => ['exp', Db::raw('="" OR FIND_IN_SET('.$this->auth->id.',check_uids) = 0')],
                    ];
                    //获取审批流程
                    $flows = Db::name('flows')->where('relation_type', 'common_seal')->where('status', 1)->find();
                    if (!empty($flows)){
                        $flows['flow_items'] = json_decode($flows['flow_items'], true);
                        //判断流程中是否有当前用户审核
                        $examine_index = 0;
                        $last_examine_indexs = [];
                        foreach ($flows['flow_items'] as $key => $value) {
                            if (in_array($this->auth->id, explode(',',$value['admin_id'])) ) {
                                $examine_index = $key + 1;
                                $last_examine_indexs[] = $key;
                                // break;
                            }
                        }
                        
                        if ($examine_index > 0) {
                            $first_children_ids = [];
                            //当前用户存在多级审核且存在第一级审核时 需要获取该用户的直属下级
                            $search_index = array_search(0, $last_examine_indexs);
                            if(count($last_examine_indexs) > 1 && $search_index !== false) {
                               //获取直属下级
                                $department_ids = Admin::getPrincipalIds($this->auth->id);
                                if ($department_ids) {
                                    $children_ids = Admin::getDepartmentAdminIds($department_ids, true);
                                    $children_ids = !empty($config_examine_admins[$this->auth->id]) ? array_merge($children_ids, explode(',', $config_examine_admins[$this->auth->id])) : $children_ids;
                                    $first_children_ids = $children_ids ?? [];
                                }
                                $last_examine_indexs = array_values(array_diff($last_examine_indexs, [0]));
                            }
                            if (!empty($first_children_ids)) {
                                if ($last_examine_indexs) {
                                    $wheres['id'] = ['exp', Db::raw('> 0 and ( (check_step_sort = 0 and admin_id in ('.implode(',', $first_children_ids).'))  OR (check_step_sort '.(count($last_examine_indexs) == 1 ? '='.$last_examine_indexs[0] : ' in ('.implode(',', $last_examine_indexs).')').' and admin_id in ('.implode(',', $adminids).')))')];
                                } else {
                                    $wheres['check_step_sort'] = 0;
                                }
                            } else {
                                $wheres['check_step_sort'] = count($last_examine_indexs) == 1 ? $last_examine_indexs[0] : ['in', $last_examine_indexs];
                            }
                            // $wheres['check_step_sort'] = $examine_index - 1;
                            $ids = Commonseal::where($wheres)->column('id');
                        }
                    }
                    break;
            }
            $count = count($ids);
            $data[$type]['count'] = $count;
            // $count = MessageModel::where(['to_staff_id' => $this->auth->id,'relation_id' => ['in', $ids],
            //     'relation_type' => MessageModel::EXAMINE_TYPE])
            //     ->count();
            if ($count) {
                $msg = MessageModel::where(['to_staff_id' => $this->auth->id, 'relation_id' => ['in', $ids],
                    'relation_type' => MessageModel::EXAMINE_TYPE])
                    ->order('id desc')
                    ->value('content');
                $msg = $msg ? : '发起一个《审批》待您处理';
                $data[$type] = ['count' => $count, 'msg' => $msg];
            }
        }

        $this->success('请求成功', $data);
    }

    /**
     * 获取通知详情
     */
    public function getInfo()
    {
        $leadsCount = MessageModel::where(['to_staff_id' => $this->auth->id, 'relation_type' => ['neq', MessageModel::EXAMINE_TYPE], 'status' => 0])->count();
        if ($leadsCount > 0) {//其他提醒消息
            $leadsDetail = MessageModel::where([
                'relation_type' => ['neq', MessageModel::EXAMINE_TYPE],
                'to_staff_id' => $this->auth->id,
                'status' => 0
            ])->order('id desc')->find();
        }

        $noticeWhere['read_admin_ids'] = ['not like', "%,{$this->auth->id},%"];

        $noticeCount = 0;//Notice::where($noticeWhere)->count();
        if ($noticeCount > 0) {
            $noticeDetail = Notice::where(['read_admin_ids' => ['not like', "%,{$this->auth->id},%"]])->order('id desc')->find();
        }

        $eventOne = 0;//Event::where([
        //     'type' => 1,
        //     'status' => ['in', [0, 1]],
        //     'start_time' => ['lt', date('Y-m-d', strtotime('+1 day'))],
        //     'staff_id|owner_staff_id' => $this->auth->id
        // ])->count();

        //系统设置特定审核人员
        $config_examine_admins = config('site.examine_admins');
        $adminids = $this->auth->adminids;
        $sale_users = $this->auth->sale_users;
        if (!empty($config_examine_admins[$this->auth->id])) {
            $adminids = array_merge($adminids,explode(',', $config_examine_admins[$this->auth->id]));
            //获取对应销售id
            $config_sale_users = (new StaffMember())->getStaffMemberIds($adminids);
            $sale_users = array_merge($sale_users,$config_sale_users);
        }

        //合同审批
        //获取审批流程
        $flows = Flows::where('relation_type', 'goods_sale')->where('status', 1)->find();
        $examine_index = 0;
        $last_examine_indexs = [];
        if (!empty($flows)){
            $flows['flow_items'] = json_decode($flows['flow_items'], true);
            //判断流程中是否有当前用户审核
            foreach ($flows['flow_items'] as $key => $value) {
                if (in_array($this->auth->id, explode(',',$value['admin_id'])) ) {
                    $examine_index = $key + 1;
                    $last_examine_indexs[] = $key;
                    // break;
                }
            }
        }
        //获取直属下级
        $children_ids = [];
        $department_ids = Admin::getPrincipalIds($this->auth->id);
        if ($department_ids) {
            $children_ids = Admin::getDepartmentAdminIds($department_ids, true);
            $children_ids = !empty($config_examine_admins[$this->auth->id]) ? array_merge($children_ids, explode(',', $config_examine_admins[$this->auth->id])) : $children_ids;
        }
        $contract = 0;//ExamineRecord::where([
        //     'relation_type' => ExamineRecord::CONTRACT_TYPE,
        //     'status' => 0,
        //     'check_staff_id' => $this->auth->id
        // ])->count();
        if ($examine_index) {
            $saleWhere = [];
            if ($sale_users) {
                $saleWhere['sale_user'] = ['IN', implode(',', $sale_users)];
            }
            $saleWhere['examine_status'] = '0';
            //当前用户存在多级审核且存在第一级审核时 需要获取该用户的直属下级
            $first_children_ids = [];
            $search_index = array_search(0, $last_examine_indexs);
            if(count($last_examine_indexs) > 1 && $search_index !== false) {
                //获取直属下级
                // $department_ids = Admin::getPrincipalIds($this->auth->id);
                // if ($department_ids) {
                //     $children_ids = Admin::getDepartmentAdminIds($department_ids, true);
                //     $children_ids = !empty($config_examine_admins[$this->auth->id]) ? array_merge($children_ids, explode(',', $config_examine_admins[$this->auth->id])) : $children_ids;
                    if ($children_ids) {
                        $first_children_ids = (new StaffMember())->getStaffMemberIds($children_ids);
                    }
                // }
                $last_examine_indexs = array_values(array_diff($last_examine_indexs, [0]));
            }
            if (!empty($first_children_ids)) {
                if ($last_examine_indexs) {
                    $saleWhere['id'] = ['exp', Db::raw('> 0 and ( (examine_index = 0 and sale_user in ('.implode(',', $first_children_ids).'))  OR (examine_index '.(count($last_examine_indexs) == 1 ? '='.$last_examine_indexs[0] : ' in ('.implode(',', $last_examine_indexs).')').' and sale_user in ('.implode(',', $sale_users).')))')];
                } else {
                    $saleWhere['examine_index'] = 0;
                }
            } else {
                $saleWhere['examine_index'] = count($last_examine_indexs) == 1 ? $last_examine_indexs[0] : ['in', $last_examine_indexs];
            }
            // $saleWhere['examine_index'] = ['<', $examine_index];
            // if ($examine_index == count($flows['flow_items'])) {
            //     $saleWhere['examine_index'] = ['>', 0];
            // }
            $saleWhere['examine_adminids'] = ['exp', Db::raw('="" OR FIND_IN_SET('.$this->auth->id.',examine_adminids) = 0')];
            $contract = GoodsSales::where($saleWhere)->count();
        }
        //报销单审批
        $expense = 0;
        if ($this->auth->check('examine/expense/examine')) {
            $wheres = [
                'admin_id' => ['in', $adminids],
                'check_status' => 1,
                'check_uids' => ['exp', Db::raw('="" OR FIND_IN_SET('.$this->auth->id.',check_uids) = 0')],
            ];
            //获取审批流程
            $flows = Db::name('flows')->where('relation_type', 'expense')->where('status', 1)->find();
            if (!empty($flows)){
                $flows['flow_items'] = json_decode($flows['flow_items'], true);
                //判断流程中是否有当前用户审核
                $examine_index = 0;
                foreach ($flows['flow_items'] as $key => $value) {
                    if (in_array($this->auth->id, explode(',',$value['admin_id'])) ) {
                        $examine_index = $key + 1;
                        // break;
                    }
                }
                if ($examine_index > 0) {
                    $wheres['check_step_sort'] = $examine_index - 1;
                    $expense = Expense::where($wheres)->count();
                }
            }
        }
        //待审核积分申请单
        $score = 0;
        if ($this->auth->check('score_apply/examine')) {
            $wheres = [
                'admin_id' => ['in', $adminids],
                'check_status' => 1,
                'check_uids' => ['exp', Db::raw('="" OR FIND_IN_SET('.$this->auth->id.',check_uids) = 0')],
            ];
            //获取审批流程
            $flows = Db::name('flows')->where('relation_type', 'score')->where('status', 1)->find();
            if (!empty($flows)){
                $flows['flow_items'] = json_decode($flows['flow_items'], true);
                //判断流程中是否有当前用户审核
                $examine_index = 0;
                $last_examine_indexs = [];
                foreach ($flows['flow_items'] as $key => $value) {
                    if (in_array($this->auth->id, explode(',',$value['admin_id'])) ) {
                        $examine_index = $key + 1;
                        $last_examine_indexs[] = $key;
                        // break;
                    }
                }
                
                if ($examine_index > 0) {
                    $first_children_ids = [];
                    //当前用户存在多级审核且存在第一级审核时 需要获取该用户的直属下级
                    $search_index = array_search(0, $last_examine_indexs);
                    if(count($last_examine_indexs) > 1 && $search_index !== false) {
                        $first_children_ids = $children_ids?$children_ids:[];
                        $last_examine_indexs = array_values(array_diff($last_examine_indexs, [0]));
                    }
                    if (!empty($first_children_ids)) {
                        if ($last_examine_indexs) {
                            $wheres['id'] = ['exp', Db::raw('> 0 and ( (check_step_sort = 0 and admin_id in ('.implode(',', $first_children_ids).'))  OR (check_step_sort '.(count($last_examine_indexs) == 1 ? '='.$last_examine_indexs[0] : ' in ('.implode(',', $last_examine_indexs).')').' and admin_id in ('.implode(',', $adminids).')))')];
                        } else {
                            $wheres['check_step_sort'] = 0;
                        }
                    } else {
                        $wheres['check_step_sort'] = count($last_examine_indexs) == 1 ? $last_examine_indexs[0] : ['in', $last_examine_indexs];
                    }
                    // $wheres['check_step_sort'] = $examine_index - 1;
                    $score = ScoreApply::where($wheres)->count();
                }
            }
        }
        //待审核积分申请单
        $common_seal = 0;
        if ($this->auth->check('kuerp/commonseal/examine')) {
            $wheres = [
                'admin_id' => ['in', $adminids],
                'check_status' => 1,
                'check_uids' => ['exp', Db::raw('="" OR FIND_IN_SET('.$this->auth->id.',check_uids) = 0')],
            ];
            //获取审批流程
            $flows = Db::name('flows')->where('relation_type', 'common_seal')->where('status', 1)->find();
            if (!empty($flows)){
                $flows['flow_items'] = json_decode($flows['flow_items'], true);
                //判断流程中是否有当前用户审核
                $examine_index = 0;
                $last_examine_indexs = [];
                foreach ($flows['flow_items'] as $key => $value) {
                    if (in_array($this->auth->id, explode(',',$value['admin_id'])) ) {
                        $examine_index = $key + 1;
                        $last_examine_indexs[] = $key;
                        // break;
                    }
                }
                
                if ($examine_index > 0) {
                    $first_children_ids = [];
                    //当前用户存在多级审核且存在第一级审核时 需要获取该用户的直属下级
                    $search_index = array_search(0, $last_examine_indexs);
                    if(count($last_examine_indexs) > 1 && $search_index !== false) {
                        $first_children_ids = $children_ids?$children_ids:[];
                        $last_examine_indexs = array_values(array_diff($last_examine_indexs, [0]));
                    }
                    if (!empty($first_children_ids)) {
                        if ($last_examine_indexs) {
                            $wheres['id'] = ['exp', Db::raw('> 0 and ( (check_step_sort = 0 and admin_id in ('.implode(',', $first_children_ids).'))  OR (check_step_sort '.(count($last_examine_indexs) == 1 ? '='.$last_examine_indexs[0] : ' in ('.implode(',', $last_examine_indexs).')').' and admin_id in ('.implode(',', $adminids).')))')];
                        } else {
                            $wheres['check_step_sort'] = 0;
                        }
                    } else {
                        $wheres['check_step_sort'] = count($last_examine_indexs) == 1 ? $last_examine_indexs[0] : ['in', $last_examine_indexs];
                    }
                    // $wheres['check_step_sort'] = $examine_index - 1;
                    $common_seal = Commonseal::where($wheres)->count();
                }
            }
        }

        //回款审批
        $receivables = 0;//ExamineRecord::where([
        //     'relation_type' => ExamineRecord::RECEIVABLES_TYPE,
        //     'status' => 0,
        //     'check_staff_id' => $this->auth->id
        // ])->count();
        //费用审批
        $consume = 0;//ExamineRecord::where([
        //     'relation_type' => ExamineRecord::CONSUME_TYPE,
        //     'status' => 0,
        //     'check_staff_id' => $this->auth->id
        // ])->count();
        //业绩目标审批
        $achievement = 0;//ExamineRecord::where([
        //     'relation_type' => ExamineRecord::ACHIEVEMENT_TYPE,
        //     'status' => 0,
        //     'check_staff_id' => $this->auth->id
        // ])->count();
        //办公审批
        $approval = 0;//ExamineRecord::where([
        //     'relation_type' => ExamineRecord::APPROVAL_TYPE,
        //     'status' => 0,
        //     'check_staff_id' => $this->auth->id
        // ])->count();
        //补卡审批
        $card = 0;//ExamineRecord::where([
        //     'relation_type' => ExamineRecord::CARD_TYPE,
        //     'status' => 0,
        //     'check_staff_id' => $this->auth->id
        // ])->count();
        //请假审批
        $leave = 0;//ExamineRecord::where([
        //     'relation_type' => ExamineRecord::LEAVE_TYPE,
        //     'status' => 0,
        //     'check_staff_id' => $this->auth->id
        // ])->count();
        //待发票审批
        $invoice = 0;//ExamineRecord::where([
        //     'relation_type'  => ExamineRecord::INVOICE_TYPE,
        //     'status'         => 0,
        //     'check_staff_id' => $this->auth->id
        // ])->count();
        $receivablesPlan = 0;//ReceivablesPlan::where([
        //     'remind_date' => ['elt', date('Y-m-d')],
        //     'status' => 0,
        //     'owner_staff_id' => $this->auth->id
        // ])->count();

        $eventsCount = 0;//Event::where([
        //     'start_time' => ['lt', date('Y-m-d', strtotime('+1 day'))],
        //     'end_time' => ['lt', date('Y-m-d', strtotime('+1 day'))],
        //     'status' => ['in', [0, 1]],
        //     'staff_id' => $this->auth->id,
        // ])->count();

        $where['create_staff_id'] = $this->auth->id;
        $where['next_time'] = array(array('egt',date('Y-m-d 00:00:00')),array('lt',date('Y-m-d 23:59:59')));
        $where['follow_type'] = ['neq', '其它'];
        $where['status'] = 0;
        // 待跟进客户
        // $where1['relation_type'] = 1;
        // $customerlist = Record::where($where)->where($where1)->column('id');
        // $customerlist1 = 0;
        // if($customerlist){
        //     $whereExit['id'] = array('in',$customerlist);
        //     $whereExit['next_time'] = array('gt',date('Y-m-d 23:59:59'));
        //     $customerlist1 = Record::where($whereExit)->count();
        // }
        $customer = 0;//count($customerlist) - $customerlist1;

        //待跟进合同
        // $where2['relation_type'] = 3;
        // $contractlist = Record::where($where)->where($where2)->column('id');
        // $contractlist1 = 0;
        // if($contractlist){
        //     $whereExitC['id'] = array('in',$contractlist);
        //     $whereExitC['next_time'] = array('gt',date('Y-m-d 23:59:59'));
        //     $contractlist1 = Record::where($whereExitC)->count();
        // }
        $contracts = 0;//count($contractlist)-$contractlist1;
        //待跟进线索
        // $where3['relation_type'] = 4;
        // $leadlist = Record::where($where)->where($where3)->column('id');
        // $leadlist1 = 0;
        // if($leadlist){
        //     $whereExitL['id'] = array('in',$leadlist);
        //     $whereExitL['next_time'] = array('gt',date('Y-m-d 23:59:59'));
        //     $leadlist1 = Record::where($whereExitL)->count();
        // }
        $lead = 0;//count($leadlist)-$leadlist1;
        //待跟进联系人
        // $where4['relation_type'] = 2;
        // $contactslist = Record::where($where)->where($where4)->column('id');
        // $contactslist1 = 0;
        // if($contactslist1){
        //     $whereExitCs['id'] = array('in',$contactslist);
        //     $whereExitCs['next_time'] = array('gt',date('Y-m-d 23:59:59'));
        //     $contactslist1 = Record::where($whereExitCs)->count();
        // }
        $contacts = 0;//count($contactslist)-$contactslist1;
        //待跟进商机
        // $where5['relation_type'] = 5;
        // $businesslist = Record::where($where)->where($where5)->column('id');
        // $businesslist1 = 0;
        // if($businesslist1){
        //     $whereExitB['id'] = array('in',$businesslist);
        //     $whereExitB['next_time'] = array('gt',date('Y-m-d 23:59:59'));
        //     $businesslist1 = Record::where($whereExitB)->count();
        // }
        $business = 0;//count($businesslist)-$businesslist1;
        //工作报告
        $workreportWhere=[
            'to_staff_id' => $this->auth->id,
            'status' => 0,
            'relation_type' => MessageModel::WORKREPORT_TYPE
        ];
        $workreportCount = MessageModel::where($workreportWhere)->count();
        if ($workreportCount > 0) {//提醒消息
            $workreportDetail = MessageModel::where($workreportWhere)->order('id desc')->find();
        }
        //发货审批
        $delivery = 0;//ExamineRecord::where([
        //     'relation_type' => ExamineRecord::DELIVERY_TYPE,
        //     'status' => 0,
        //     'check_staff_id' => $this->auth->id
        // ])->count();
        //入库审批
        $instock = 0;//ExamineRecord::where([
        //     'relation_type' => ExamineRecord::INSTOCK_TYPE,
        //     'status' => 0,
        //     'check_staff_id' => $this->auth->id
        // ])->count();
        //商品出库审批
        $outstock = 0;//ExamineRecord::where([
        //     'relation_type' => ExamineRecord::OUTSTOCK_TYPE,
        //     'status' => 0,
        //     'check_staff_id' => $this->auth->id
        // ])->count();
        //提醒消息
        $data = [
            'leads' => ['count' => $leadsCount, 'msg' => $leadsDetail['content'] ?? '暂无消息'],//提醒消息
            'workreport' => ['count' => $workreportCount, 'msg' => $workreportDetail['content'] ?? '暂无消息'],//工作报告
            'examine' => ['count' => $contract + $receivables+$consume+$achievement+$approval+$card+$leave+$invoice+$delivery+$instock+$outstock+$expense + $score + $common_seal,
                'msg' => '审批消息提醒'],//提醒消息
            'notice' => ['count' => $noticeCount, 'msg' => $noticeDetail['title'] ?? '暂无消息'],//系统公告
            'agent' => [
                'count' => $eventOne  + $receivablesPlan+ $customer + $contracts + $lead + $contacts + $business,
                'msg' => '您有新的待办事项需要处理！'
            ],//待办事项
            'task' => [
                'count' => $eventsCount,
                'msg' => '即将超时的任务提醒！'
            ],//超时任务
            'total' => $leadsCount  + $noticeCount + $eventOne + $contract + $receivables + $receivablesPlan + $eventsCount+ $customer + $contracts + $lead + $contacts + $business+$consume+$achievement+$approval+$card+$leave+$invoice+$delivery+$instock+$outstock+$expense+$score+ $common_seal,
            'enableExamine' => $this->auth->check('examine/expense/examine') || $this->auth->check('examine/goods_sales/examine')  || $this->auth->check('score_apply/examine')|| $this->auth->check('kuerp/commonseal/examine'),
            'userinfo' => $this->auth->getUserinfo()
        ];
        $this->success('请求成功', $data);
    }

    public function newsReadAll(){
        $whereNew = ['status'=>0,'to_staff_id' => $this->auth->id ,'relation_type'=>['not in','examine']];
        $res = MessageModel::where($whereNew)->update(['read_time' => time(), 'status' => 1]);
        if ($res !== false) {
            return $this->success('操作成功');
        } else {
            return $this->error('操作失败');
        }
    }
}
